import { ExclamationCircleOutlined,UploadOutlined  } from "@ant-design/icons";
import {
  Button,
  Empty,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Space,
  Spin,
  Tag,
  Tooltip,
  Upload
} from "antd";
import moment from "moment";
import { useEffect, useState } from "react";
import { request } from "../../utils/request";
import { basePath } from "../../utils/tool";
import styles from "./Account.module.scss";
const { TextArea } = Input;
export default function OrderList() {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType] = useState("1");
  const [modalVisible, setModalVisible] = useState(false);
  const [orderItem, setOrderItem] = useState({});
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [returnModalVisible, setReturnModalVisible] = useState(false);
  const [percent, setPercent] = useState(0);
  const [photos, setPhoto] = useState([]);
  const [showRemind, setShowRemind] = useState(false);
  const getOrderList = async (type) => {
    setLoading(true);
    const ret = await request(`${basePath()}/api/order/list`, {
      userId: JSON.parse(localStorage.getItem("user")).id,
      current: 1,
      pageSize: 50,
      type: type,
    });
    if (ret.code === 100000) {
      setList(ret.data.rows);
    } else {
      message.error("get bag list error");
    }
    setLoading(false);
  };
  const changeType = (e) => {
    console.log("e", e);
    setType(e.target.value);
    getOrderList(e.target.value);
  };
  const handleReceive = async (data) => {
    console.log("data", data);

    const ret = await request(`${basePath()}/api/order/receiveGoods`, {
      orderNo: data.orderNo,
    });
    if (ret.code === 100000) {
      message.success("You have success confirm receving");
      getOrderList(type);
    } else {
      message.error("Something goes error");
    }
  };
  const onFinish = async (values) => {
    console.log("photo", photos);
    setLoading(true);
    const ret = await request(`${basePath()}/api/order/applyRefund`, {
      orderNo: values.orderNo,
      id: orderItem.id,
      reason: values.reason,
      photos: photos.length ? photos.join(",") : "",
    });
    if (ret.code === 100000) {
      setShowRemind(true);
      getOrderList(type);
    }
    setLoading(false);
  };
  const onFinish1 = async (values) => {
   
    setLoading(true);
    const ret = await request(`${basePath()}/api/order/returnItems`, {
      returnTrackingNo: values.returnTrackingNo,
      id: orderItem.id,
      expressCompany: values.expressCompany
  
    });
    if (ret.code === 100000) {
     message.success('You have success submit your request')
      getOrderList(type);
      setReturnModalVisible(false)
    }
    setLoading(false);
  };
  const handleChange = (info) => {
    if (info.event) {
      const percent = Math.floor((info.event.loaded / info.event.total) * 100);
      setPercent(percent);
    }
    if (info.file.status !== "uploading") {
    }
    if (info.file.status === "done") {
      message.success(`${info.file.name} upload success`);
      const imgurl = info.file.response.data;
      console.log("imgurl", imgurl);
      const arr = [...photos];
      arr.push(imgurl[0].url);
      setPhoto(arr);
    }
    if (info.file.status === "error") {
      message.error(`${info.file.name} upload error`);
    }
  };
  const beforeUpload = (e) => {
    console.log("beforupload", e.size);
    if (e.size > 1024 * 1024) {
      message.warning("the photo's size can not large than 1M");
      return false;
    }
    return true;
  };
  useEffect(() => {
    getOrderList(1);
  }, []);
  return (
    <div className={styles.OrderList}>
      <Radio.Group
        defaultValue="1"
        style={{
          marginTop: 2,
          marginBottom: 16,
          marginRight: 16,
        }}
        onChange={changeType}
      >
        <Space>
          <Radio.Button value="1">All</Radio.Button>
        </Space>
        <Space>
          <Radio.Button value="3">Waiting for shiping</Radio.Button>
        </Space>
        <Space>
          <Radio.Button value="4">Waiting for receive</Radio.Button>
        </Space>
        <Space>
          <Radio.Button value="5">Done</Radio.Button>
        </Space>
      </Radio.Group>
      <Spin spinning={loading}>
        {!list.length && <Empty />}
        <div className={styles.OrderListBox}>
          {list.map((item) => (
            <div className={styles.OrderBox} key={item.orderNo}>
              <div className={styles.orderHeader}>
                <span>{item.orderNo}</span>
                <span>
                  {moment(item.createTime).format("YYYY-MM-DD HH:mm:ss")}
                </span>
              </div>
              {item.children.map((items, index) => (
                <div className={styles.orderContent} key={index}>
                  {[1, 2].includes(items.returnStatus) && (
                    <Button
                      type="primary"
                      className={styles.refund}
                      onClick={() => {
                        setOrderItem(items);
                        setModalVisible(true);
                      }}
                    >
                      Refund
                    </Button>
                  )}
                  {items.returnStatus === 3 && (
                    <Tag color="orange" className={styles.refund}>
                      Refund in review
                    </Tag>
                  )}
                  {items.returnStatus === 4 && (
                    <div className={styles.refund}>
                      <Tag color="orange">Return Reject</Tag>
                      <Tooltip placement="top" title={items.rejectReson}>
                        <a className={styles.more}>view more</a>
                      </Tooltip>
                    </div>
                  )}
                  {items.returnStatus === 5 && (
                    <div className={styles.refund}>
                      <Tag color="orange">Return Accept</Tag>
                      <Tooltip placement="top" title={items.rejectReson}>
                        <a
                          className={styles.more}
                          onClick={() => {setReturnModalVisible(true);setOrderItem(items)}}
                        >
                          Click here to return this item
                        </a>
                      </Tooltip>
                    </div>
                  )}
                  {items.returnStatus === 6 && (
                    <div className={styles.refund}>
                      <Tag color="orange">Refund Review</Tag>
                      
                    </div>
                  )}
                  <img
                    className={styles.OrderBoxImg}
                    src={items.url.length ? items.url[0].url : ""}
                  ></img>
                  <div className={styles.OrderBoxRight}>
                    <span className={styles.name}>{items.productName}</span>
                    <div className={styles.propBox}>
                      <span
                        className={styles.propBoxColor}
                        style={{ background: items.colorName }}
                      ></span>
                      <span>{items.sizeName}</span>
                    </div>

                    <div className={styles.OrderBoxRightItemPriceBox}>
                      <div className={styles.OrderBoxRightItemPrice}>
                        <span>itemPrice</span>
                        <span>${items.goodsPrice}</span>
                      </div>
                      <div className={styles.OrderBoxRightItemPrice}>
                        <span>Ouantity</span>
                        <span>{items.qty}</span>
                      </div>
                      <div className={styles.OrderBoxRightItemPrice}>
                        <span>Total Price</span>
                        <span>${items.totalAmount}</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
              <div className={styles.orderFooter}>
                <div className={styles.total}>
                  <span className={styles.tip}>
                    Shipping cost: ${item.shipAmount}
                  </span>
                  <span className={styles.tip}>Total: ${item.payAmount}</span>
                </div>
                {item.shipStatus === 1 && (
                  <div className={styles.btnGroup}>
                    <Button type="dashed" className={styles.footerBtn}>
                      Package Tracking
                    </Button>
                    <Button
                      type="primary"
                      className={styles.footerBtn}
                      onClick={() => {
                        Modal.confirm({
                          title: "Receiving confirmation",
                          icon: <ExclamationCircleOutlined />,
                          content: "Do you recevied the pakeage?",
                          okText: "Yes",
                          cancelText: "No",
                          onOk: () => handleReceive(item),
                        });
                      }}
                    >
                      Receiving confirmation
                    </Button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </Spin>
      <Modal
        footer={null}
        width={900}
        visible={returnModalVisible}
        onCancel={() => {
          setReturnModalVisible(false);
          setShowRemind(false);
        }}
        title="Return item"
      >
        <div className={styles.address}>
          <h1> Please return your items to:</h1>
          NINAMOKA DESIGN INC <br />
          14650 VALLEY BLVD LA PUENTE, CA 91746 <br />
          UNITED STATES <br />
          Once your return is received and inspected, your refund will be
          processed as soon as possible. <br />
        </div>

        <Form form={form1} layout="vertical" onFinish={onFinish1}>
          <Form.Item
            label="Your Return Tracking number"
            name="returnTrackingNo"
            rules={[
              {
                required: true,
                message: "please enter refund reason",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="Express company"
            name="expressCompany"
            rules={[
              {
                required: true,
                message: "please enter refund reason",
              },
            ]}
          >
            <Select
              options={[
                { label: "USPS", value: "USPS" },
                { label: "Fedex", value: "Fedex" },
                { label: "UPS", value: "UPS" },
                { label: "Ontrac", value: "Ontrac" },
                { label: "DHL", value: "DHL" },
                { label: "JB", value: "JB" },
                { label: "Robinson", value: "Robinson" },
                { label: "Ryder", value: "Ryder" },
                { label: "Expeditors", value: "Expeditors" },
                { label: "Penske", value: "Penske" },
                { label: "Lineage", value: "Lineage" },
                { label: "NFI", value: "NFI" },
              ]}
            />
          </Form.Item>
          <Form.Item>
            <Button
              className={styles["body-button"]}
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              Submit
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        footer={null}
        width={900}
        visible={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setShowRemind(false);
        }}
        title="Apply of refund"
      >
        {showRemind ? (
          <p>
            You have success apply refund and we will review and feedback to you
            according to the email.
          </p>
        ) : (
          <Form form={form} layout="vertical" onFinish={onFinish}>
            <Form.Item
              label="Reason(25-500 characters)"
              name="reason"
              rules={[
                {
                  required: true,
                  message: "please enter refund reason",
                },
              ]}
            >
              <TextArea minLength={25} maxLength={500} rows={4} />
            </Form.Item>

            <Form.Item label="Upload Photos" name="photo">
              <Upload
                action={`${basePath()}/api/aws/upload`}
                name="file"
                onChange={handleChange}
                maxCount={3}
                multiple={true}
                accept="image/png, image/jpeg,image/gif,video/*"
                beforeUpload={beforeUpload}
                showUploadList={false}
              >
                <Button icon={<UploadOutlined />}>upload</Button>
              </Upload>
            </Form.Item>
            {photos.length > 0 && (
              <Form.Item>
                {photos.map((item, index) => {
                  return (
                    <Image key={index} src={item} width={100} height={100} />
                  );
                })}
              </Form.Item>
            )}

            <Form.Item>
              <Button
                className={styles["body-button"]}
                type="primary"
                htmlType="submit"
                loading={loading}
                block
              >
                Submit
              </Button>
            </Form.Item>
          </Form>
        )}
      </Modal>
    </div>
  );
}
